import Vue from 'vue';
import Cookies from 'js-cookie';
import Router from 'vue-router';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  base: '',
  routes: [
    {
      path: '/',
      name: 'home',
      redirect: 'layout',
    },
    {
      path: '/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue'),
    },
    {
      path: '/password',
      name: 'password',
      component: () => import('@/views/Password.vue'),
    },
  ],
});

router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    const usernam = Cookies.get('username')
    if (usernam) {
      next()
    } else {
      next({ name: 'login' })
    }
  }
});

export default router;